package pers.cnzdy.tutorial.Chapter9_Perception_Media.Section4_Video;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.widget.VideoView;

import java.io.File;

import pers.cnzdy.tutorial.R;

public class MediaActivity extends AppCompatActivity {
    private VideoView videoView;
    private Button    playBtn;
    private Button    pauseBtn;
    private Button    replayBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_media);

        int checkPermission = ContextCompat.checkSelfPermission(
                MediaActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (checkPermission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MediaActivity.this,
                    new String[]{
                            Manifest.permission.WRITE_EXTERNAL_STORAGE },
                    1);
        } else {
            Log.d("Media", "sdCard: " + Environment.getExternalStorageDirectory());

            File file = new File(Environment.getExternalStorageDirectory(),
                    "androidstudio.3gp");
            if (!file.exists()) {
                Toast.makeText(this,
                        "视频文件路径错误", Toast.LENGTH_SHORT).show();
                return;
            }

            playBtn   = findViewById(R.id.play_video_btn);
            pauseBtn  = findViewById(R.id.pause_video_btn);
            replayBtn = findViewById(R.id.resume_video_btn);

            videoView = findViewById(R.id.video_view);
            videoView.setVideoPath(file.getPath());
        }
    }

    public void play(View view) {
        if (!videoView.isPlaying()) {
            videoView.start();
        }
    }

    public void pause(View view) {
        if (videoView.isPlaying()) {
            videoView.pause();
        }
    }

    public void resume(View view) {
        if (videoView.isPlaying()) {
            videoView.resume();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (videoView != null)
            videoView.suspend();
    }
}
